/**
 * @Title: LoginFeign.java
 * @Description: 用一句话描述该文件做什么
 * @author zhangxin
 * @date 2019年3月13日
 */
package com.fortune.rainshine.controller;

import com.fortune.rainshine.feign.common.RedisFeign;
import com.fortune.rainshine.feign.common.SmsSendFeign;
import com.fortune.rainshine.feign.service.ShopFeign;
import com.fortune.rainshine.feign.system.UserFeign;
import com.fortune.rainshine.feign.system.UserFeignNoTokken;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.entity.LoginRecordEntity;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.model.LoginDtoModel;
import com.fortune.rainshinecommon.model.LoginParamsModel;
import com.fortune.rainshinecommon.model.ShopModel;
import com.fortune.rainshinecommon.model.system.LoginRecord;
import com.fortune.rainshinecommon.model.system.User;
import com.fortune.rainshinecommon.util.EndecryptUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxin
 * @ClassName: LoginFeign
 * @Description: 登录逻辑
 * @date 2019年3月13日
 */
@RestController
@RequestMapping("login")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    RedisFeign redisFeign;
    @Autowired
    SmsSendFeign smsSendFeign;
    @Autowired
    UserFeignNoTokken userFeignNoTokken;
    @Autowired
    ShopFeign shopFeign;
    @Autowired
    UserFeign userFeign;

    @Value("${smsSend.number}")
    private Integer number;

    /**
     * @Title: sendSms
     * @Description: 发送验证码
     * @author zhangxin
     * @date 2019年3月14日
     */
    @ApiOperation(value = "发送验证码", notes = "获取短信验证码")
    @ApiImplicitParam(name = "loginParams", value = "只需传递phone的值即可", required = true, dataType = "LoginParamsModel")
    @PostMapping("send_sms")
    public MsgModel sendSms(@RequestBody LoginParamsModel loginParams) {
        // SysUsers user =
        // userFeignNoTokken.getUserInfoByAccount(loginParams.getUserAccount()));
        // // 获取图形验证码，若为空则说明而已调用短信接口
        // HttpServletRequest request = ((ServletRequestAttributes)
        // RequestContextHolder.getRequestAttributes())
        // .getRequest();
        // String vcode =
        // request.getSession().getAttribute("vercode").toString().toUpperCase();
        //
        // if (user != null && vcode != null) {
        // Boolean exists = redisFeign.exists(RedisConstantEnum.SMS.getMessage() +
        // loginParams.getPhone());
        // Boolean bo = false;
        // if (exists) {
        // redisFeign.delete(RedisConstantEnum.SMS.getMessage() +
        // loginParams.getPhone());
        // }
        // Gson gson = new Gson();
        // String code = RandomNumUtil.getRandNum(number);
        // SmsParamsModel smsParams = new SmsParamsModel();
        // smsParams.setCode(code);
        // String jsonParams = gson.toJson(smsParams);
        // try {
        // bo = smsSendFeign.sendSms(loginParams.getPhone(), jsonParams);
        // if (bo) {
        // redisFeign.set(RedisConstantEnum.SMS.getMessage() + loginParams.getPhone(),
        // code, 60000);
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // return new MsgModel(ResultCode.FAILURE);
        // }
        // } else {
        // return new MsgModel(ResultCode.NOTEXISTS);
        // }
        return new MsgModel(ResultCode.SUCCESS);
    }

    @PostMapping("login")
    public MsgModel smsLogin(@RequestBody LoginParamsModel loginParams) {
        User user = userFeignNoTokken.getUserInfo(loginParams.getUserAccount());
        try {
            if (user != null) {
                if(user.getState() != 0){
                    return new MsgModel("此账号已停用", ResultCode.FAILURE);
                }
                String password = EndecryptUtil.encrytMd5(loginParams.getPassword(), loginParams.getUserAccount(), 3);
                if (user.getPassword().equals(password)) {
                    LoginDtoModel appLoginDto = userFeignNoTokken.userSmsLogin(loginParams);
                    //2 - boss,4 - 招商，5 - 店长
                    if(appLoginDto.getRoleId() == 2 || appLoginDto.getRoleId() == 4 || appLoginDto.getRoleId() == 5){
                        //门店id
                        List<ShopModel> shopList = Optional.ofNullable(shopFeign.getShopsByUserId2(appLoginDto.getUserId()))
                                .orElse(Lists.newArrayList());
                        if (shopList.isEmpty()) {
                            return new MsgModel("无正常营业门店", ResultCode.FAILURE);
                        }
                        List<Map<String,Object>> mapList = shopList.stream().map(e -> {
                            Map<String,Object> map = new HashMap<>();
                            map.put("shopId", e.getId());
                            map.put("shopName", e.getShopName());
                            return map;
                        }).collect(Collectors.toList());
                        appLoginDto.setShops(mapList);
                    }
                    if(appLoginDto.getRoleId() == 3){
                        ShopModel shopModel = shopFeign.getShopByShopId2(user.getShopId());
                        if(shopModel.getId() == null){
                            return new MsgModel("门店已停用", ResultCode.FAILURE);
                        }
                        Map<String,Object> map = new HashMap<>();
                        map.put("shopId", shopModel.getId());
                        map.put("shopName", shopModel.getShopName());
                        List<Map<String,Object>> mapList = Lists.newArrayList();
                        mapList.add(map);
                        appLoginDto.setShops(mapList);
                    }
                    redisFeign.set(RedisConstantEnum.TOKEN.getMessage() + appLoginDto.getUserId(),
                            appLoginDto.getUserToken());
//                    redisFeign.set(appLoginDto.getUserToken(), appLoginDto.getUserId().toString());
                    // 添加到登录日志
                    LoginRecordEntity loginRecordEntity = new LoginRecordEntity();
                    loginRecordEntity.setUserId(user.getUserId());
                    loginRecordEntity.setOsName(loginParams.getOsName());
                    loginRecordEntity.setDevice(loginParams.getDevice());
                    userFeign.addLoginRecord(loginRecordEntity);
                    return new MsgModel(ResultCode.SUCCESS, appLoginDto);
                } else {
                    return new MsgModel(ResultCode.PASSWORDERROR);
                }
            } else {
                return new MsgModel(ResultCode.NOTEXISTS);
            }
        } catch (Exception e) {
            logger.error("smsLogin =====> {}", e);
            return new MsgModel(ResultCode.FAILURE);
        }
    }
}
